<?php

namespace app\common\service;

use app\common\model\user\UserAuthLog;
use app\common\model\user\UserGroup;
use think\image\Exception;
use tmcore\base\BaseService;
use app\common\cache\SmsVerifyCache;
use tmcore\exceptions\ValidateException;
use app\common\model\user\User;

class UserService extends BaseService
{
    /**
     * 用户注册
     * @param array $params
     * @return bool|array
     * @throws ValidateException|\think\db\exception\DbException
     */
    public function register($params) {

        if(empty($params['account']) || empty($params['password']) || empty($params['channel'])) throw new ValidateException('注册参数不全');

        $account = $params['account'];
        $password = $params['password'];
        $channel = $params['channel'];
        $mobile = $params['mobile'] ?? '';

        if(User::where(['account' => $account])->count()) throw new ValidateException('账号已被占用，请更换账号');

        // 验证码检验
        if(!empty($params['mobile']) && isset($params['code'])) {
            (new SmsVerifyCache)->verifySmsCode($params['mobile'], 'user_register', $params['code']);
        }

        if($mobile && User::where(['mobile' => $mobile])->count()) throw new ValidateException('手机号已被占用，请更换手机号');

        try {
            $group_id = UserGroup::where(['is_default' => 1])->value('id');

            $data = [
                'user_token' => com_random(16,'0123456789'),
                'group_id' => $params['group_id'] ?? intval($group_id),
                'account' => $account,
                'password' => User::getPassword($password, 'user_register'),
                'avatar' => empty($params['avatar']) ? config('core.default_image')['user_avatar']:$params['avatar'],
                'mobile' => $params['mobile'] ?? '',
                'nickname' => $params['nickname'] ?? 'u_' . com_random(6,'0123456789'),
                'real_name' => $params['real_name'] ?? '',
                'birthday' => $params['birthday'] ?? '',
                'id_card' => $params['id_card'] ?? '',
                'sex' => $params['sex'] ?? 0,
                'email' => $params['email'] ?? '',
                'admin_id' => $params['admin_id'] ?? 0,
                'last_ip' => app('request')->ip(),
                'last_time' => time(),
                'status' => 1
            ];

            $uid = User::add($data, true);
            if(!$uid) throw new ValidateException('注册失败');

            // 用户授权记录
            $this->userAuth($uid, $channel, $params['openid']??'');

            if(!empty($params['mobile'])) (new SmsVerifyCache)->deleteSmsCode($params['mobile'], 'user_register');

            return [
                'id' => $uid,
                'account' => $data['account'],
                'nickname' => $data['nickname'],
                'avatar' => $data['avatar'],
                'mobile' => $data['mobile'],
            ];

        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 修改用户信息
     * @param string $type
     * @param array $params
     * @return bool
     * @throws ValidateException
     */
    public function updateInfo($type,$params) {

        if(empty($params['id'])) throw new ValidateException('用户ID不可为空');

        try {

            $data = [];

            switch ($type) {
                case 'update_password': //修改密码
                    $data['password'] = User::getPassword($params['password'], 'user_register');
                    break;
                case 'update_mobile': //修改手机号
                    $data['mobile'] = $params['mobile'];
                    break;
                case 'update_email': //修改邮箱
                    $data['email'] = $params['email'];
                    break;
                case 'update_info': //修改用户信息
                    if(!empty($params['account']))$data['account'] = $params['account'];
                    if(!empty($params['password']))$data['password'] = $params['password'];
                    if(!empty($params['mobile']))$data['mobile'] = $params['mobile'];
                    if(!empty($params['group_id']))$data['group_id'] = $params['group_id'];
                    if(isset($params['nickname']))$data['nickname'] = $params['nickname'];
                    if(isset($params['real_name']))$data['real_name'] = $params['real_name'];
                    if(isset($params['id_card']))$data['id_card'] = $params['id_card'];
                    if(isset($params['avatar']))$data['avatar'] = $params['avatar'];
                    if(isset($params['sex']))$data['sex'] = $params['sex'];
                    if(!empty($params['status']))$data['status'] = $params['status'];
                    break;
                default:
                    throw new Exception('更新类型参数有误');
                    break;
            }

            $this->updateVerify($data, $params['id']);

            User::update($data,['id' => $params['id']]);
            return true;
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 校验用户更新
     * @param $params
     * @param $uid
     * @return bool
     * @throws Exception
     */
    public function updateVerify($params, $uid) {

        if(!empty($params['account'])) {
            if(User::where([['id', '<>', $uid], ['account', '=', $params['account']]])->count()) {
                throw new Exception('账号已被占用，请更换账号');
            }
        }

        if(!empty($params['password'])) {
            if(User::where(['id' => $uid])->value('password') == $params['password']) {
                throw new Exception('新密码不可与原密码相同');
            }
        }

        if(!empty($params['mobile'])) {
            if(User::where([['id', '<>', $uid], ['mobile', '=', $params['mobile']]])->count()) {
                throw new Exception('手机号已被占用，请更换手机号');
            }
        }

        return true;
    }

    /**
     * 用户授权
     * @param $uid
     * @param $channel
     * @param string $openid
     * @param string $unionid
     * @return UserAuthLog|bool|\think\Model
     * @throws \think\db\exception\DbException
     */
    public function userAuth($uid, $channel, $openid = '', $unionid = '') {

        $count = UserAuthLog::where(['uid' => $uid, 'channel' => $channel, 'openid' => $openid])->count();
        if($count) {
            return true;
        } else {
            return UserAuthLog::create([
                'uid' => $uid,
                'openid' => $openid,
                'unionid' => $unionid,
                'ua' => app('request')->header('User-Agent'),
                'channel' => $channel
            ]);
        }
    }

    /**
     * 执行事件
     * @param $scene
     * @param $uid
     * @param array $params
     * @return bool
     */
    public function callEvent($scene, $uid, $params = []) {
        switch ($scene) {
            case 'user_register': //用户注册
                event('UserRegister', ['id' => $uid]);
                event('NoticeMsg', ['scene' => 'user_register', 'params' => ['id' => $uid]]);
                break;
            case 'user_login': //用户登录
                event('UserLogin', ['id' => $uid]);
                event('NoticeMsg', ['scene' => 'user_login', 'params' => ['id' => $uid]]);
                break;
            default:
                break;
        }
        return true;
    }


}